%% Data Logger 004 27/11/2012 BP
clear;
clf;

%% Define Serial Port Name
port = input ('Input Port Name  ','s');
log = input ('Input Log File Name  ','s');

%% Create & Open Serial Port
SER = serial(port,'Terminator','lf','baud',9600);
set(SER,'DataTerminalReady','off');
fopen(SER);
fwrite(SER,240); % this is sending one byte to Arduino to initialise the sampling

%% Create Log File

fID=fopen([log,'.csv'],'w+');

%% Read Data 
vals=2048;

L=zeros(vals,2);
X=1:vals;

current_row=1;

while 1
    l = fgetl(SER);             %read line from serial
    fprintf(fID,[l,'\n']);      % Write data directly to a file
    a = eval(['[',l,']']);      %extract data from string
    if(size(a,2)==2)
        L(current_row,:)=a;     %add data to new line in array
        
        % Get elements of L as a ring buffer
        R=[current_row+1:vals,1:current_row]; % this is going from the current position, to the end and then back to front
        
        plot(X,L(R,2));         %Plot data on graph
        drawnow;                %force figure to redraw
        
        % Increment buffer position, loop back if at the end
        current_row=mod(current_row,vals)+1;
    end
end

%When end function, end and fclose(SER) to close serial port before
%clearing variables.